//
//  YYSecretInput.swift
//  YYProject
//
//  Created by FishWithoutWings on 2018/1/9.
//  Copyright © 2018年 陆文宇. All rights reserved.
//

import UIKit

class YYSecretInput: UITextField, UITextFieldDelegate {
    
    var doneClosure: ((String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        delegate = self
        borderStyle = .none
        keyboardType = .numberPad
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        delegate = self
        borderStyle = .none
        keyboardType = .numberPad
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        for subview in textField.subviews {
            subview.alpha = 0
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        for subview in textField.subviews {
            subview.alpha = 0
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard text!.count < 6 else {
            return false
        }
        
        if string == "" {
            var t = text!
            t.removeLast()
            text = t
        } else {
            text = text! + string
        }
        
        setNeedsDisplay()
        if text!.count == 6 {
            SVProgressHUD.showStatus("正在处理...")
            delay(0.3, {
                self.doneClosure?(self.text!)
            })
        }
        return false
    }
    
    override func draw(_ rect: CGRect) {
        #imageLiteral(resourceName: "password_in").draw(in: rect)
        
        let w = rect.width * 0.05
        let h = w
        let y = rect.height * 0.5 - w / 2
        var x: CGFloat = 0
        let padding = rect.width * (1.0 / 12.0 - 0.025)
        
        for i in 0 ..< text!.count {
            x = padding + CGFloat(i) * (w + 2 * padding)
            #imageLiteral(resourceName: "yuan").draw(in: CGRect(x: x, y: y, width: w, height: h))
        }
    }
    
}

